package com.jtbd.handler.mybatis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jtbd.client.ObjectMapperClient;
import jakarta.annotation.Resource;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.ObjectUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class ArrayListStringTypeHandler extends BaseTypeHandler<ArrayList<String>> {
    private ObjectMapper objectMapper;

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, ArrayList<String> parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, ObjectMapperClient.writeValue(parameter));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ArrayList<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return readData(rs.getString(columnName));
    }

    private ArrayList<String> readData(String value) {
        try {
            if (!ObjectUtils.isEmpty(value)) {
                return ObjectMapperClient.readValue(value, new TypeReference<>() {
                });
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public ArrayList<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return readData(rs.getString(columnIndex));
    }

    @Override
    public ArrayList<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return readData(cs.getString(columnIndex));
    }
}
